package com.anysoft.base;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.anysoft.R;
import com.anysoft.event.TimeOutEvent;
import com.anysoft.utils.MentorLogger;
import com.anysoft.view.CustomMarqueeTextView;
import com.anysoft.view.HProgressBarLoading;
import com.anysoft.view.dialog.IcbcDialog;
import com.anysoft.web.SelectWarmPromptActivity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ren.yale.android.cachewebviewlib.CacheWebView;
import ren.yale.android.cachewebviewlib.WebViewCache;

import static com.anysoft.HostConstant.HOST_WEB_URL_HEADER;

/**
 * Created by wwq on 2017/3/16.
 */

public class BaseWebviewWithCacheActivity extends BaseActivity {


    @BindView(R.id.rl_title_layout_2)
    public RelativeLayout rl_title_layout_2;
    @BindView(R.id.leftButton2)
    public Button leftButton2;
    @BindView(R.id.rightButton2)
    public TextView rightButton2;
    @BindView(R.id.shareButton)
    public ImageView shareButton;
    @BindView(R.id.iv_title_line)
    public ImageView iv_title_line;

    @BindView(R.id.shareButtonTitle1)
    public ImageView shareButtonTitle1;

    @BindView(R.id.tv_title2)
    public CustomMarqueeTextView tv_title2;
    @BindView(R.id.tv_sub_title2)
    public TextView tv_sub_title2;


    @BindView(R.id.wv)
    public CacheWebView mWebView;

    public String loadUrl;
    public Intent mIntent = new Intent();
    @BindView(R.id.leftButton)
    public Button leftButton;
    @BindView(R.id.rightButton)
    public TextView rightButton;
    @BindView(R.id.rl_title_white_layout)
    public RelativeLayout rl_title_white_layout;
    @BindView(R.id.title)
    public TextView title;
    @BindView(R.id.cmtv_title)
    public CustomMarqueeTextView cmtvTitle;
    @BindView(R.id.titlebar)
    public FrameLayout titlebar;
    @BindView(R.id.iv_leftButton)
    public ImageView ivLeftButton;
    @BindView(R.id.tv_item_web_error)
    public TextView tvItemWebError;
    @BindView(R.id.ll_item_web_error)
    public LinearLayout llItemWebError;
    @BindView(R.id.top_progress)
    public HProgressBarLoading top_progress;

    public boolean isLoadError = false;

    public boolean isCanPressBack = true;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_webview_base);
        ButterKnife.bind(this);
        isShowDialog = false;
        titlebar.setVisibility(View.VISIBLE);
        rl_title_layout_2.setVisibility(View.GONE);
        mWebView.setCacheStrategy(WebViewCache.CacheStrategy.FORCE);
        CacheWebView.servicePreload(this, loadUrl);//通过启动Service来预加载，不影响UI线程
        tvItemWebError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.setVisibility(View.GONE);
                llItemWebError.setVisibility(View.GONE);
                initView(loadUrl);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (mWebView != null){
            mWebView.onPause();
        }
        super.onPause();
    }

    public void initUrl(String action, String param) {
        loadUrl = HOST_WEB_URL_HEADER + action + ".html?isFromApp=true&" + param;
        Log.e(TAG, "loadUrl=" + loadUrl);
    }

    public void isShowTitleBar(boolean bool) {
        titlebar.setVisibility(bool ? View.VISIBLE : View.GONE);

    }

    private boolean isFinishGo;

    public void initView(String url) {

        isFinishGo = false;
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }

            //会连接url页面的操作,true则自己处理,false则交由webView自己处理
            @Override
            public boolean shouldOverrideUrlLoading(WebView webview, String url) {
                MentorLogger.Log(TAG, "shouldOverrideUrlLoading url=" + url);
                onshouldOverrideUrlLoadingCallBack(webview, url);
                return true;
            }

            //开始执行会走的方法
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
            }

            //执行完毕会走的方法
            @Override
            public void onPageFinished(WebView view, String url) {
                isFinishGo = true;
                String title = view.getTitle();
                if (!isLoadError) {
                    mWebView.setVisibility(View.VISIBLE);
                    llItemWebError.setVisibility(View.GONE);
                } else {
                    isLoadError = false;
                    mWebView.setVisibility(View.GONE);
                    llItemWebError.setVisibility(View.VISIBLE);
                }

                if ("网页无法打开".equals(title) || title.contains("404")) {
                    mWebView.setVisibility(View.GONE);
                    llItemWebError.setVisibility(View.VISIBLE);
                }

                onPageFinishedMine(view, url);
            }

            //网页打开失败会执行
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                isLoadError = true;
                mWebView.setVisibility(View.GONE);
                llItemWebError.setVisibility(View.VISIBLE);
                super.onReceivedError(view, request, error);
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
//                MentorLogger.Log("WisdomWebviewTab", "onReceivedHttpError");
//                if ("404".equals(errorResponse.getStatusCode() + "")) {
//                    if (isFinishGo) {
//                        isLoadError = true;
//                    }
//                    mWebView.setVisibility(View.GONE);
//                    llItemWebError.setVisibility(View.VISIBLE);
//                }
//                super.onReceivedHttpError(view, request, errorResponse);
            }

            //网页打开失败会执行
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                if (isShowDialog) {
                    showDialog(failingUrl);
                }
            }

            //WebView不能加载https,需要重写这个方法
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed(); //授权所有网站的证书
            }
        });

        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                top_progress.setCurProgress(newProgress);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                MentorLogger.Log(TAG, "onJsAlert:" + message);
                result.confirm();
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                MentorLogger.Log(TAG, "onJsConfirm:" + message);
                result.confirm();
                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                MentorLogger.Log(TAG, "onJsPrompt:" + url);
                result.confirm();
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
        });
        mWebView.loadUrl(url);
        mWebView.removeJavascriptInterface("searchBoxJavaBridge_");
        mWebView.removeJavascriptInterface("accessibility");
        mWebView.removeJavascriptInterface("accessibiltyTraversal");
    }

    private boolean isShowDialog = false;

    public void setLoadErrorShowDialog(boolean isShow) {
        isShowDialog = isShow;
    }

    private void showDialog(final String url) {

        IcbcDialog dialog = new IcbcDialog(this);

        dialog.setAnimationEnable(true);
        dialog.setCancelable(false);
        dialog.setTitle("提示");
        dialog.setContentText("网页加载失败！");
        dialog.setEditTextType(false);
        dialog.setNegativeListener("重试", new IcbcDialog.OnNegativeListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                mWebView.loadUrl(url);
                dialog.dismiss();
            }
        });
        dialog.setPositiveListener("返回首页", new IcbcDialog.OnPositiveListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
                finish();
            }
        }).show();
    }

    /**
     * 顶部显示哪个布局 1：普通布局 默认 2：标题有两行内容布局
     *
     * @param index
     */
    public void showTitleIndex(int index) {
        if (index == 2) {
            titlebar.setVisibility(View.GONE);
            rl_title_layout_2.setVisibility(View.VISIBLE);
        } else {
            titlebar.setVisibility(View.VISIBLE);
            rl_title_layout_2.setVisibility(View.GONE);
        }
    }

    public void onshouldOverrideUrlLoadingCallBack(WebView webview, String url) {
        MentorLogger.Log(TAG, "url=" + url);
        if (url.contains("prompt.html")) {
            mIntent.setClass(mActivity, SelectWarmPromptActivity.class);
            mIntent.putExtra("url", url);
            startActivity(mIntent);
        } else {
            webview.loadUrl(url);
        }
    }

    @OnClick({R.id.leftButton, R.id.leftButton2})
    public void onClick() {
        if (isCanPressBack) {
            finish();
        }
    }

    public static HashMap<String, String> handleUrlParams(String url) {
        HashMap<String, String> hm = new HashMap<String, String>();
        if (url.contains("?") && url.indexOf("?") != url.length() - 1) {
            String params = url.substring(url.indexOf("?") + 1);
            if (params.contains("&")) {
                String[] paramArr = params.split("&");
                for (int i = 0; i < paramArr.length; i++) {
                    String str = paramArr[i];
                    if (str.contains("=")) {
                        hm.put(str.substring(0, str.indexOf("=")),
                                str.substring(str.indexOf("=") + 1,
                                        str.length()));
                    }
                }
            } else {
                if (params.contains("=")) {
                    hm.put(params.substring(0, params.indexOf("=")),
                            params.substring(params.indexOf("=") + 1,
                                    params.length()));
                }
            }
        }
        return hm;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTimeOutCallBack(TimeOutEvent event) {
        if (event.isSuccess) {
            finish();
        }
    }

    @OnClick({R.id.leftButton, R.id.rightButton, R.id.tv_item_web_error})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leftButton:
                break;
            case R.id.rightButton:
                break;
            case R.id.tv_item_web_error:
                mWebView.setVisibility(View.GONE);
                llItemWebError.setVisibility(View.GONE);
                initView(loadUrl);
                break;
        }
    }

    public void onPageFinishedMine(WebView view, String url) {

    }

    @Override
    public void onBackPressed() {
        if (isCanPressBack) {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        destoryWebView();
        super.onDestroy();
    }

    public void destoryWebView() {
        if (mWebView != null) {
            mWebView.stopLoading(); //停止加载
            ((ViewGroup) mWebView.getParent()).removeView(mWebView); //把webview从视图中移除
            mWebView.removeAllViews(); //移除webview上子view
            mWebView.destroy(); //销毁webview自身
            mWebView = null;
        }
    }
}
